package com.egoo.ticket.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.egoo.ticket.server.dao.*;
import com.egoo.ticket.server.pojo.dto.*;
import com.egoo.ticket.server.pojo.entity.*;
import com.egoo.ticket.server.pojo.enums.FieldEnum;
import com.egoo.ticket.server.pojo.vo.InteractiveDataVo;
import com.egoo.ticket.server.pojo.vo.VisibleRangeVo;
import com.egoo.ticket.server.pojo.vo.WorkOrderTypeNodeVo;
import com.egoo.ticket.server.pojo.vo.WorkOrderTypeVo;
import com.egoo.ticket.server.service.*;
import com.egoo.ticket.server.utils.activiti.ActCommonUtils;
import com.egoo.ticket.server.utils.common.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class WorkOrderTypeServiceImpl implements WorkOrderTypeService {

	@Autowired
	EwsUserDao ewsUserDao;
	@Autowired
	WorkOrderTypeDao workOrderTypeDao;
	@Autowired
	WorkOrderTypeNodeService workOrderTypeNodeService;
	@Autowired
	WorkOrderTypeMenuService workOrderTypeMenuService;
	@Autowired
	WorkOrderFilterMenuDao workOrderFilterMenuDao;
	@Autowired
	WorkOrderFilterMenuService workOrderFilterMenuService;
	@Autowired
	WorkOrderTypeMenuDao workOrderTypeMenuDao;
	@Autowired
	FormTemplateDao formTemplateDao;
	@Autowired
	private WorkOrderTypeNodeDao workOrderTypeNodeDao;
	@Autowired
	private WorkOrderStatusDao workOrderStatusDao;
	@Autowired
	private WorkOrderFieldReflectDao workOrderFieldReflectDao;
	@Autowired
	private WorkOrderFieldReflectService workOrderFieldReflectService;
	@Autowired
	CommonUtil commonUtil;
	@Autowired
	private EripDataSynService eripDataSynService;

	/**
	 * TODO 创建工单类型和类型节点
	 *
	 * @param tag        tag为1：创建工单类型，tag为2：更新工单类型
	 * @param jsonObject 2
	 * @author: victor_tang
	 * @createtime: 2020/3/3 16:04
	 * @return: boolean
	 */
	public boolean createOrUpdateWorkOrderType(Integer tag, JSONObject jsonObject) {
		//创建activiti的xml的输入
		CreateActivitiXmlDto createActivitiXmlDto = new CreateActivitiXmlDto();
		String userId = jsonObject.getString("userId");
		String tenantId = jsonObject.getString("tenantId");
		EwsUser ewsUser = ewsUserDao.selectById(userId);
		JSONObject workordertypeformInfo = jsonObject.getJSONObject("workordertypeformInfo");
		Long id = workordertypeformInfo.getLong("workordertypeUuid") - 1;
		Long previousId = jsonObject.getLong("previousId");
		String name = workordertypeformInfo.getString("workordertypeName");
		Integer useStatus = workordertypeformInfo.getInteger("workordertypeEnable");
		createActivitiXmlDto.setWorkOrderTypeName("_" + name);
		Timestamp time = new Timestamp(System.currentTimeMillis());

		JSONObject newworkordernodeInfo = jsonObject.getJSONObject("newworkordernodeInfo");
		Long workOrderTypeNodeVoStartId = newworkordernodeInfo.getLong("uuid");

		//组装工单类型可见人
		WorkOrderTypeVo workOrderTypeVo1 = assembleWorkOrderVisiabler(jsonObject);
		//创建工单类型
		Integer workOrdertypeVersion = 1;
		if (tag == 1) {
			createActivitiXmlDto.setWorkOrderTypeId(id);
			//创建工单类型
			WorkOrderTypeVo workOrderType = new WorkOrderTypeVo();
			workOrderType.setLastUserId(userId);
			workOrderType.setLastUserName(ewsUser.getName());
			workOrderType.setLastUpdateTime(time);
			workOrderType.setId(id);
			workOrderType.setName(name);
			workOrderType.setUseStatus(useStatus);
			workOrderType.setDeleteStatus(0);
			workOrderType.setEditStatus(0);
			workOrderType.setMaxVersion(workOrdertypeVersion);
			workOrderType.setContent(jsonObject);
			workOrderType.setTypeVisiableIds(workOrderTypeVo1.getTypeVisiableIds());
			workOrderType.setVisiableType(workOrderTypeVo1.getVisiableType());
			workOrderType.setTenantId(tenantId);
			log.info("新建工单类型的content: {}", jsonObject);
			workOrderTypeDao.create(workOrderType);

		} else {
			createActivitiXmlDto.setWorkOrderTypeId(previousId);

			//更新工单类型
			WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(previousId);
			// 工单类型版本信息
			workOrdertypeVersion = getWorkOrderTypeVersion(previousId);
			workOrderTypeVo.setMaxVersion(workOrdertypeVersion);
			workOrderTypeVo.setId(previousId);
			workOrderTypeVo.setName(name);
			workOrderTypeVo.setContent(jsonObject);
			workOrderTypeVo.setUseStatus(useStatus);
			workOrderTypeVo.setLastUserId(userId);
			workOrderTypeVo.setLastUserName(ewsUser.getName());
			workOrderTypeVo.setLastUpdateTime(time);
			workOrderTypeVo.setTypeVisiableIds(workOrderTypeVo1.getTypeVisiableIds());
			workOrderTypeVo.setVisiableType(workOrderTypeVo1.getVisiableType());
			workOrderTypeVo.setTenantId(tenantId);
			workOrderTypeDao.updateWorkOrderType(workOrderTypeVo);
			id = previousId;
		}
		//获取创建类型 true为外部创建，false为内部创建(创建，更新都需要创建自定义字段)
		boolean flag = jsonObject.getJSONObject("newworkordernodeInfo").getBoolean("createWay");
		if (flag) {
			List<WorkOrderFieldReflect> workOrderFieldReflects = getWorkOrderFieldReflect(jsonObject);
			for (WorkOrderFieldReflect workOrderFieldReflect : workOrderFieldReflects) {
				workOrderFieldReflect.setWorkOrderTypeId(id.toString());
				workOrderFieldReflect.setTenantId(tenantId);
				workOrderFieldReflect.setWorkOrderTypeNodeId(workOrderTypeNodeVoStartId.toString());
			}
			workOrderFieldReflectDao.create(workOrderFieldReflects);
		}

		//创建开始节点
		WorkOrderTypeNodeVo workOrderTypeNodeVoStart = new WorkOrderTypeNodeVo();

		String formKeySign = newworkordernodeInfo.getString("formKeySign");
		workOrderTypeNodeVoStart.setId(workOrderTypeNodeVoStartId);
		createActivitiXmlDto.setWorkOrderTypeNodeVoStartId(workOrderTypeNodeVoStartId);
		workOrderTypeNodeVoStart.setWorkOrderTypeId(id);
		//设置节点标识，1为开始节点
		workOrderTypeNodeVoStart.setTag(1);
		String workOrderTypeNodeVoName = newworkordernodeInfo.getString("nodeName");
		workOrderTypeNodeVoStart.setName(workOrderTypeNodeVoName);
		createActivitiXmlDto.setWorkOrderTypeNodeVoStartName(workOrderTypeNodeVoName);
		Integer workOrderTypeNodeVoFormTemplateId = newworkordernodeInfo.getInteger("formKey");
		//更新模板的使用次数
		workOrderTypeNodeVoStart.setFormTemplateId(workOrderTypeNodeVoFormTemplateId);
		workOrderTypeNodeVoStart.setContent(newworkordernodeInfo);
		workOrderTypeNodeVoStart.setTenantId(tenantId);

		workOrderTypeNodeVoStart.setWorkOrderTypeVersion(workOrdertypeVersion);
		//获取模板内容
//		workOrderTypeNodeVoStart.setFormTempalteContent(getFormtemplateContent(workOrderTypeNodeVoFormTemplateId));
		workOrderTypeNodeVoStart.setFormTempalteContent(getTemplateContent(newworkordernodeInfo));
		workOrderTypeNodeVoStart.setFormKeySign(formKeySign);
		workOrderTypeNodeService.create(workOrderTypeNodeVoStart);
		//循环创建流转节点
		JSONArray workordernodeInfo = jsonObject.getJSONArray("workordernodeInfo");
		Integer workordernodeInfoSize = workordernodeInfo.size();
		//xml的流转节点集合
		List<WorkOrderTypeNodeVo> flowNodeList = new ArrayList<>();
		for (int i = 0; i < workordernodeInfoSize; i++) {
			JSONObject runNode = workordernodeInfo.getJSONObject(i);
			//创建节点字段映射
			createNodeFieldReflect(runNode,id,tenantId);
			WorkOrderTypeNodeVo workOrderTypeRunNodeVo = new WorkOrderTypeNodeVo();
			Long workOrderTypeRunNodeVoId = runNode.getLong("uuid");
			workOrderTypeRunNodeVo.setId(workOrderTypeRunNodeVoId);
			workOrderTypeRunNodeVo.setWorkOrderTypeId(id);
			String workOrderTypeRunNodeVoName = runNode.getString("nodeName");
			workOrderTypeRunNodeVo.setName(workOrderTypeRunNodeVoName);
			flowNodeList.add(workOrderTypeRunNodeVo);
			Integer workOrderTypeRunNodeVoFormTemplateId = runNode.getInteger("formKey");
			workOrderTypeRunNodeVo.setFormTemplateId(workOrderTypeRunNodeVoFormTemplateId);
			workOrderTypeRunNodeVo.setContent(runNode);
			workOrderTypeRunNodeVo.setDistributeWay(runNode.getString("handleMethods"));
			workOrderTypeRunNodeVo.setTenantId(tenantId);
			workOrderTypeRunNodeVo.setWorkOrderTypeVersion(workOrdertypeVersion);
			workOrderTypeRunNodeVo.setWorkOrderTypeVersion(workOrdertypeVersion);
			workOrderTypeRunNodeVo.setFormTempalteContent(getFormtemplateContent(workOrderTypeRunNodeVoFormTemplateId));
			workOrderTypeNodeService.create(workOrderTypeRunNodeVo);

		}
		//生成activiti的xml
		String filePath = System.getProperty("user.dir") + "/modelXml";
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdir();
		}
		filePath += File.separator + name + id + ".bpmn20.xml";
		createActivitiXmlDto.setFlowNodeList(flowNodeList);
		createActivitiXmlDto.setXmlUrl(filePath);
		XmlUtils.createActivitiXml(createActivitiXmlDto);
		//部署activiti的xml
		ActCommonUtils.deploy(filePath, name);
		return true;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 最新获取初始节点模板content
	 * @Param:
	 * @return:
	 * @Date: 2020/5/20
	 */
	private JSONObject getTemplateContent(JSONObject newworkordernodeInfo) {
		JSONArray classifyList = newworkordernodeInfo.getJSONArray("classifyList");
		String formKeySign = newworkordernodeInfo.getString("formKeySign");
//		if条件处理选择一个模板逻辑，else处理多模板配置
		if (ConstantCode.WorkOrderNodeInfo.FORM_KEY_SIGN_ONE.equals(formKeySign)&&CollectionUtils.isEmpty(classifyList)){
			Integer formId = newworkordernodeInfo.getInteger("formKey");
			FormTemplate formTemplate = formTemplateDao.selectById(formId);
			if (formTemplate==null || formTemplate.getContent()==null) {
				log.info("工单类型节点所选模板信息或模板content为空！");
				throw new RuntimeException("工单类型节点所选模板信息或模板content为空！");
			}
			return formTemplate.getContent();
		}else {
			List<Integer> idList = getNextIds(classifyList);

			List<FormTemplate> formTemplates = formTemplateDao.selectByIds(idList);
			JSONArray jsonArrayContent = new JSONArray();
			JSONObject jsonObjectTemplate = new JSONObject();
			for (FormTemplate template: formTemplates
				 ) {
				JSONObject content = template.getContent();
				content.put("formId",template.getId());
				jsonArrayContent.add(content);
			}
			jsonObjectTemplate.put("list",jsonArrayContent);
			return jsonObjectTemplate;
		}


	}

	/**
	 * @Author: Donny_dong
	 * @Description: 获取树结构入口
	 * @Param:
	 * @return:
	 * @Date: 2020/5/21
	 */
	public List<Integer> getNextIds(JSONArray dataSource){
		ArrayList<Integer> formIdList = new ArrayList<>();
		for (int i = 0; i < dataSource.size(); i++) {
			JSONObject jsonObject = dataSource.getJSONObject(i);
			formIdList = handleData(jsonObject,formIdList);
		}
		log.info(""+formIdList);
		List<Integer> collect = formIdList.stream().distinct().collect(Collectors.toList());
		return collect;
	}

	/**
	 * @Author: Donny_dong
	 * @Description: 递归获取每个子级的id
	 * @Param:
	 * @return:
	 * @Date: 2020/5/21
	 */
	private ArrayList<Integer> handleData(JSONObject jsonObject, ArrayList<Integer> formIdList) {
		formIdList.add(jsonObject.getInteger("formType"));
		JSONArray children = jsonObject.getJSONArray("children");
		if (CollectionUtils.isEmpty(children)) {
			return formIdList;
		}
		for (int i = 0; i < children.size(); i++) {
			JSONObject jsonObjectChildren = children.getJSONObject(i);
			formIdList = handleData(jsonObjectChildren,formIdList);
		}
		return formIdList;
	}


	/**
	 * @Author: Donny_dong
	 * @Description: 创建节点字段映射
	 * @Param:
	 * @return:
	 * @Date: 2020/5/15
	 */
	private void createNodeFieldReflect(JSONObject runNode, Long id, String tenantId) {
		String nodeFlowType = runNode.getString("nodeSign");
		if (FieldEnum.FLOW_OUT.getCode().equals(nodeFlowType)) {
			WorkOrderFieldReflectDto workOrderFieldReflectDto = new WorkOrderFieldReflectDto();
			JSONArray workOrderReflectArray = runNode.getJSONArray("setOptions");
			String nodeId = runNode.getString("uuid");
			workOrderFieldReflectDto.setWorkOrderTypeId(id.toString());
			workOrderFieldReflectDto.setWorkOrderFieldReflect(workOrderReflectArray);
			workOrderFieldReflectDto.setWorkOrderTypeNodeId(nodeId);
			workOrderFieldReflectService.creat(workOrderFieldReflectDto);
		}

	}

	/**
	 * TODO 根据模板id获取模板内容
	 * @author: victor_tang
	 * @createtime: 2020/4/23 14:32
	 * @param workOrderTypeNodeVoFormTemplateId 1
	 * @return: com.alibaba.fastjson.JSONObject
	 */
	private JSONObject getFormtemplateContent(Integer workOrderTypeNodeVoFormTemplateId) {

		FormTemplate formTemplate = formTemplateDao.selectById(workOrderTypeNodeVoFormTemplateId);
		if (formTemplate==null || formTemplate.getContent()==null) {
			log.info("工单类型节点所选模板信息或模板content为空！");
			throw new RuntimeException("工单类型节点所选模板信息或模板content为空！");
		}
		return formTemplate.getContent();
	}

	/**
	 * TODO 新增工单类型版本信息
	 * @author: victor_tang
	 * @createtime: 2020/4/23 14:04
	 * @param workOrderTypeId 1
	 * @return: void
	 */
	private Integer getWorkOrderTypeVersion(Long workOrderTypeId) {
		WorkOrderTypeNodeVo workOrderTypeNodeVo = workOrderTypeNodeDao.selectMaxVersionByWorkOrderTypeId(workOrderTypeId);
		Integer version = null;
		if (workOrderTypeNodeVo==null || workOrderTypeNodeVo.getWorkOrderTypeVersion()==null) {
			// 首次创建
			version = 1;
		} else {
			// 二次编辑
			version = workOrderTypeNodeVo.getWorkOrderTypeVersion()+1;
		}
		return version;
	}

	/**
	 * @return void
	 * @Author Donny_Dong
	 * @Description 工单类型可见人的数据组装
	 * @Date 11:59 2020/1/19
	 * @Param [jsonObject]
	 **/
	private WorkOrderTypeVo assembleWorkOrderVisiabler(JSONObject jsonObject) {
		JSONObject workordertypeVisiableRangle = jsonObject.getJSONObject("workordertypeformInfo").getJSONObject("workordertypeVisiableRangle");
		// 可见范围类型（部门dept 角色role 用户user）
		String idType = workordertypeVisiableRangle.getString("firstClassify");
		// 可见范围值ids
		WorkOrderTypeVo workOrderTypeVo = new WorkOrderTypeVo();
		if ("all".equals(idType)){
			workOrderTypeVo.setVisiableType(idType);
			workOrderTypeVo.setTypeVisiableIds(idType);
		}else if (ConstantCode.UserRoleDeptType.DEPT.equals(idType)){
			JSONArray jsonArrayIds = workordertypeVisiableRangle.getJSONArray("userValue");
			JSONArray deptUserValue = workordertypeVisiableRangle.getJSONArray("deptUserValue");
			if (CollectionUtils.isEmpty(deptUserValue)) {
				List<List> idList = JSON.parseArray(jsonArrayIds.toJSONString(), List.class);
				String ids = ArrayUtils.toString(idList).replace("[", "").replace("]", "").replaceAll(" ", "");
				workOrderTypeVo.setVisiableType(idType);
				workOrderTypeVo.setTypeVisiableIds(ids);
			}else {
				List<String> list = JSON.parseArray(deptUserValue.toJSONString(), String.class);
				String join = StringUtils.join(list, ",");
				workOrderTypeVo.setVisiableType(ConstantCode.UserRoleDeptType.USER);
				workOrderTypeVo.setTypeVisiableIds(join);
			}
		}
		else {
			JSONArray jsonArrayIds = workordertypeVisiableRangle.getJSONArray("userValue");
			List<String> idList = JSON.parseArray(jsonArrayIds.toJSONString(), String.class);
			String ids = StringUtils.join(idList, ",");
			workOrderTypeVo.setVisiableType(idType);
			workOrderTypeVo.setTypeVisiableIds(ids);
		}
		return workOrderTypeVo;
	}

	/**
	 * @return void
	 * @Author Donny_Dong
	 * @Description //TODO 组装工单映射实体对象
	 * @Date 11:58 2019/12/26
	 * @Param [jsonObject]
	 **/
	private List<WorkOrderFieldReflect> getWorkOrderFieldReflect(JSONObject jsonObject) {

		JSONArray jsonArrayWorkOrderFieldReflect = jsonObject.getJSONArray(ConstantCode.CreateWorkOrderFieldReflectKey.WORKORDERFIELDREFLECTKEY);
		List<WorkOrderFieldReflect> workOrderFieldReflects = JSONArray.parseArray(jsonArrayWorkOrderFieldReflect.toJSONString(), WorkOrderFieldReflect.class);
		return workOrderFieldReflects;
	}

	/**
	 * TODO 获取工单类型创建方式
	 *
	 * @param jsonObject 1
	 * @author: victor_tang
	 * @createtime: 2020/2/5 18:31
	 * @return: boolean
	 */
	private boolean workOrderTypeCreateWay(JSONObject jsonObject) {

		boolean createWay = jsonObject.getJSONObject("newworkordernodeInfo").getBoolean("createWay");
		if (createWay == true) {
			return createWay;
		}
		return createWay;
	}

	/**
	 * TODO 创建工单类型
	 *
	 * @param jsonObject 1
	 * @author: victor_tang
	 * @createtime: 2020/2/5 18:30
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse create(JSONObject jsonObject) {
		// 创建并部署工单类型
		createOrUpdateWorkOrderType(1, jsonObject);

		Long previousId = jsonObject.getLong("previousId");
		if (previousId == 0) {
			//新建工单类型菜单
			String tenantId = jsonObject.getString("tenantId");
			String userId = jsonObject.getString("userId");
			JSONObject workordertypeformInfo = jsonObject.getJSONObject("workordertypeformInfo");
			String name = workordertypeformInfo.getString("workordertypeName");
			Long id = workordertypeformInfo.getLong("workordertypeUuid") - 1;
			createTypeMenuAndFilterMenu(userId, name, id, tenantId);
		}

		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, "新建成功！");
	}

	/**
	 * TODO 创建工单类型菜单和过滤器菜单
	 *
	 * @param userId            1
	 * @param workOrderTypeName 2
	 * @param workOrderTypeId   3
	 * @param tenantId          4
	 * @author: victor_tang
	 * @createtime: 2020/3/3 16:03
	 * @return: void
	 */
	public void createTypeMenuAndFilterMenu(String userId, String workOrderTypeName,
											Long workOrderTypeId, String tenantId) {
		// 创建工单类型菜单
		createTypeMenu(userId, workOrderTypeId, workOrderTypeName, tenantId);
//		//创建系统默认过滤器（正泰项目暂时注释）
//		createSysFilterMenu(workOrderTypeId, workOrderTypeName, tenantId);
	}

	/**
	 * TODO 创建类型菜单
	 *
	 * @param userId            1
	 * @param workOrderTypeId   2
	 * @param workOrderTypeName 3
	 * @author: victor_tang
	 * @createtime: 2020/3/3 15:31
	 * @return: void
	 */
	private void createTypeMenu(String userId, long workOrderTypeId,
								String workOrderTypeName, String tenantId) {
		WorkOrderTypeMenuInputDto workOrderTypeMenuInputDto = new WorkOrderTypeMenuInputDto();
		workOrderTypeMenuInputDto.setId(((Long)System.currentTimeMillis()).intValue());
		workOrderTypeMenuInputDto.setUserId(userId);
		workOrderTypeMenuInputDto.setMenuName(workOrderTypeName);
		workOrderTypeMenuInputDto.setMenuDesc(workOrderTypeName);
		workOrderTypeMenuInputDto.setWorkOrderTypeId(workOrderTypeId);
		workOrderTypeMenuInputDto.setWorkOrderTypeName(workOrderTypeName);
		Integer ordering = workOrderTypeMenuService.selectOrderMax();
		workOrderTypeMenuInputDto.setOrdering(ordering);
		workOrderTypeMenuInputDto.setStatus(0);
		workOrderTypeMenuInputDto.setTagId(0);
		workOrderTypeMenuInputDto.setTagName("自定义");
		VisibleRangeVo visibleRange = new VisibleRangeVo();
		visibleRange.setType(ConstantCode.UserRoleDeptType.ALL);
		visibleRange.setNameList("");
		JSONArray value = new JSONArray();
		visibleRange.setValue(value);
		workOrderTypeMenuInputDto.setVisibleRange(visibleRange);
		workOrderTypeMenuInputDto.setTenantId(tenantId);
		workOrderTypeMenuInputDto.setId(((Long)System.currentTimeMillis()).intValue());
		//创建工类类型菜单
		workOrderTypeMenuService.insertMenu(workOrderTypeMenuInputDto);
	}

	/**
	 * TODO 创建系统过滤器
	 *
	 * @param workOrderTypeId   1
	 * @param workOrderTypeName 2
	 * @author: victor_tang
	 * @createtime: 2020/3/3 14:53
	 * @return: java.utils.List<com.egoo.ews.service.vo.WorkOrderFilterMenu>
	 */
	private void createSysFilterMenu(long workOrderTypeId, String workOrderTypeName, String tenantId) {
		List<WorkOrderFilterMenu> workOrderFilterMenus = new ArrayList<>();

		//获取当前最大排序值
		Integer orderMax = workOrderFilterMenuDao.selectOrderMax();
		if (orderMax == null) {
			orderMax = 0;
		}
		// 初始化系统过滤器公共字段
		WorkOrderFilterMenu workOrderFilterMenu = initSysFilterMenuInfo(workOrderTypeId, workOrderTypeName, tenantId);

		// 所有工单列表过滤器菜单
		JSONObject filterCondition1 = JSON.parseObject("{}");
		WorkOrderFilterMenu workOrderFilterMenu1 = handleDifferSysFilterMenuData(workOrderFilterMenu
				, ConstantCode.SysFilter.ALL_FILTER_NAME, ConstantCode.SysFilter.ALL_FILTER_NAME, filterCondition1,
				orderMax + 1);
		workOrderFilterMenus.add(workOrderFilterMenu1);

		// 我创建的过滤器菜单
		JSONObject filterCondition2 = JSON.parseObject("{}");
		WorkOrderFilterMenu workOrderFilterMenu2 = handleDifferSysFilterMenuData(workOrderFilterMenu
				, ConstantCode.SysFilter.CREATE_FILTER_NAME,
				ConstantCode.SysFilter.CREATE_FILTER_NAME, filterCondition2, orderMax + 2);
		workOrderFilterMenus.add(workOrderFilterMenu2);

		// 编辑中工单过滤器菜单
		JSONObject filterCondition3 = JSON.parseObject("{}");
		WorkOrderFilterMenu workOrderFilterMenu3 = handleDifferSysFilterMenuData(workOrderFilterMenu
				, ConstantCode.SysFilter.EDIT_FILTER_NAME,
				ConstantCode.SysFilter.EDIT_FILTER_NAME, filterCondition3, orderMax + 3);
		workOrderFilterMenus.add(workOrderFilterMenu3);


		// 我关注的工单过滤器菜单
		JSONObject filterCondition4 = JSON.parseObject("{}");
		WorkOrderFilterMenu workOrderFilterMenu4 = handleDifferSysFilterMenuData(workOrderFilterMenu
				, ConstantCode.SysFilter.MONITOR_FILTER_NAME,
				ConstantCode.SysFilter.MONITOR_FILTER_NAME, filterCondition4,
				orderMax + 4);
		workOrderFilterMenus.add(workOrderFilterMenu4);

		// 待处理工单过滤器菜单
		JSONObject filterCondition5 = JSON.parseObject("{}");
		WorkOrderFilterMenu workOrderFilterMenu5 = handleDifferSysFilterMenuData(workOrderFilterMenu
				, ConstantCode.SysFilter.WAIT_HANDLE_FILTER_NAME,
				ConstantCode.SysFilter.WAIT_HANDLE_FILTER_NAME, filterCondition5,
				orderMax + 5);
		workOrderFilterMenus.add(workOrderFilterMenu5);

		if (workOrderFilterMenus.size() > 0) {
			workOrderFilterMenuDao.insertByBatch(workOrderFilterMenus);
		}
	}

	/**
	 * TODO 组装系统过滤器数据
	 *
	 * @param workOrderFilterMenuBo 1
	 * @param name                  2
	 * @param menuDesc              3
	 * @param filterCondition       4
	 * @param order                 5
	 * @author: victor_tang
	 * @createtime: 2020/3/3 15:10
	 * @return: com.egoo.ews.service.vo.WorkOrderFilterMenu
	 */
	private WorkOrderFilterMenu handleDifferSysFilterMenuData(WorkOrderFilterMenu workOrderFilterMenuBo, String name,
                                                              String menuDesc, JSONObject filterCondition, Integer order) {
		WorkOrderFilterMenu workOrderFilterMenu = new WorkOrderFilterMenu();
		BeanUtils.copyProperties(workOrderFilterMenuBo, workOrderFilterMenu);
		workOrderFilterMenu.setName(name);
		workOrderFilterMenu.setMenuDesc(menuDesc);
		workOrderFilterMenu.setFilterCondition(filterCondition);
		workOrderFilterMenu.setOrdering(order);
		return workOrderFilterMenu;
	}

	/**
	 * TODO 初始化系统过滤器数据
	 *
	 * @param workOrderTypeId   1
	 * @param workOrderTypeName 2
	 * @author: victor_tang
	 * @createtime: 2020/3/3 14:55
	 * @return: com.egoo.ews.service.vo.WorkOrderFilterMenu
	 */
	private WorkOrderFilterMenu initSysFilterMenuInfo(long workOrderTypeId, String workOrderTypeName, String tenantId) {
		WorkOrderFilterMenu workOrderFilterMenu = new WorkOrderFilterMenu();
		workOrderFilterMenu.setWorkOrderTypeId(workOrderTypeId);
		workOrderFilterMenu.setWorkOrderTypeName(workOrderTypeName);
		workOrderFilterMenu.setStatus(1);
		workOrderFilterMenu.setTagId(1);
		workOrderFilterMenu.setTagName("系统内置");
		workOrderFilterMenu.setCreateUserId("0");
		workOrderFilterMenu.setCreateUserName("系统");
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		workOrderFilterMenu.setCreateTime(timestamp);
		workOrderFilterMenu.setLastUserId("0");
		workOrderFilterMenu.setLastUserName("系统");
		workOrderFilterMenu.setLastUpdateTime(timestamp);
		workOrderFilterMenu.setFilterMenuVisibleType(ConstantCode.UserRoleDeptType.ALL);
		workOrderFilterMenu.setFilterMenuVisibleIds("");
		workOrderFilterMenu.setTenantId(tenantId);
		return workOrderFilterMenu;
	}

	@Override
	public PageOutputDto selectAll(Integer currentPage, Integer pageSize) {
		List<WorkOrderTypeVo> formTemplateList = workOrderTypeDao.selectAll((currentPage - 1) * pageSize, pageSize);
		Integer total = workOrderTypeDao.selectTotal();
		PageOutputDto pageOutputDto = new PageOutputDto();
		pageOutputDto.setList(formTemplateList);
		pageOutputDto.setTotal(total);
		return pageOutputDto;
	}

	/**
	 * 根据工单类型名称分页获取工单类型
	 *
	 * @param name
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@Override
	public PageOutputDto selectByName(String name, Integer currentPage, Integer pageSize, String userId, String tenantId) {
		PageHelper.startPage(currentPage, pageSize);
		List<WorkOrderTypeVo> workOrderTypeList = workOrderTypeDao.selectByName(name, userId, tenantId);
		PageInfo<WorkOrderTypeVo> workOrderTypeVoPageInfo = new PageInfo<>(workOrderTypeList);
		PageOutputDto pageOutputDto = new PageOutputDto();
		pageOutputDto.setTotal(workOrderTypeVoPageInfo.getTotal());
		pageOutputDto.setList(workOrderTypeList);
		return pageOutputDto;
	}

	@Override
	public WorkOrderTypeVo selectById(Long id) {
		return workOrderTypeDao.selectById(id);
	}

	/**
	 * 更新启停状态
	 *
	 * @param id
	 * @param userId
	 * @param useStatus
	 * @return
	 */
	@Override
	public Integer updateUseStatus(Long id, String userId, Integer useStatus) {
		WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(id);
		EwsUser ewsUser = ewsUserDao.selectById(userId);
		workOrderTypeVo.setLastUserId(userId);
		workOrderTypeVo.setLastUserName(ewsUser.getName());
		Timestamp time = new Timestamp(System.currentTimeMillis());
		workOrderTypeVo.setLastUpdateTime(time);
		workOrderTypeVo.setUseStatus(useStatus);
		Integer result = workOrderTypeDao.updateUseStatus(workOrderTypeVo);
		//更新工单类型的content
		updateContent(id, useStatus);
		return result;
	}

	/**
	 * 根据id获取工单类型的属性内容
	 *
	 * @param id
	 * @return
	 */
	@Override
	public JSONObject selectContentById(Long id,String tenantId) {
		WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(id);
//		JSONObject jsonObject = JSON.parseObject(workOrderTypeVo.getContentString());
		JSONObject jsonObject = workOrderTypeVo.getContent();
		//查看创建节点中的出现的工单状态
		JSONObject newworkordernodeInfo = jsonObject.getJSONObject("newworkordernodeInfo");
		JSONArray sequenceFlows = newworkordernodeInfo.getJSONArray("sequenceFlows");
		for (int i = 0; i < sequenceFlows.size(); i++) {
			JSONObject sequenceFlow = sequenceFlows.getJSONObject(i);
			String status = sequenceFlow.getString("status");
			Integer statusId = Integer.parseInt(status);
			WorkOrderStatus workOrderStatus = workOrderStatusDao.selectById(statusId,tenantId);
			if (null == workOrderStatus) {
				sequenceFlow.put("status", "3");
			}
		}
		//验证流转节点
		JSONArray workordernodeInfo = jsonObject.getJSONArray("workordernodeInfo");
		for (int j = 0; j < workordernodeInfo.size(); j++) {
			JSONObject workordernodeInfo1 = workordernodeInfo.getJSONObject(j);
			if (!workordernodeInfo1.containsKey("afterviewstatus")){
				continue;
			}
			String afterviewstatus = workordernodeInfo1.getString("afterviewstatus");
			Integer afterviewstatusId = Integer.parseInt(afterviewstatus);
			WorkOrderStatus workOrderStatus = workOrderStatusDao.selectById(afterviewstatusId,tenantId);
			if (null == workOrderStatus) {
				workordernodeInfo1.put("afterviewstatus", "3");
			}
			JSONArray sequenceFlows1 = workordernodeInfo1.getJSONArray("sequenceFlows");
			if (CollectionUtils.isEmpty(sequenceFlows1)){
				continue;
			}
			for (int k = 0; k < sequenceFlows1.size(); k++) {
				JSONObject sequenceFlow = sequenceFlows1.getJSONObject(k);
				String status = sequenceFlow.getString("status");
				Integer statusId = Integer.parseInt(status);
				WorkOrderStatus workOrderStatus1 = workOrderStatusDao.selectById(statusId,tenantId);
				if (null == workOrderStatus1) {
					sequenceFlow.put("status", "3");
				}
			}
		}
		return jsonObject;
	}

	public Integer updateEditStatus(Long id, String userId, Integer ediStatus) {
		WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(id);
		EwsUser ewsUser = ewsUserDao.selectById(userId);
		workOrderTypeVo.setLastUserId(userId);
		workOrderTypeVo.setLastUserName(ewsUser.getName());
		Timestamp time = new Timestamp(System.currentTimeMillis());
		workOrderTypeVo.setLastUpdateTime(time);
		workOrderTypeVo.setEditStatus(ediStatus);
		return workOrderTypeDao.updateEditStatus(workOrderTypeVo);
	}
	/**
	 * TODO 修改工单类型
	 * @author: victor_tang
	 * @createtime: 2020/4/9 19:07
	 * @param jsonObject 1
	 * @return: com.egoo.ews.service.utils.DBResponse
	 */
	@Override
	public DbResponse updateContent(JSONObject jsonObject) {
		//修改原来的工单类型的编辑状态
		Long previousId = jsonObject.getLong("previousId").longValue();
		String userId = jsonObject.getString("userId");
		String tenantId = jsonObject.getString("tenantId");
		JSONObject workordertypeformInfo = jsonObject.getJSONObject("workordertypeformInfo");
		String name = workordertypeformInfo.getString("workordertypeName");
		Long id = workordertypeformInfo.getLong("workordertypeUuid") - 1;
		if (previousId != 0) {
			//更新该工单类型的工单类型菜单
			workOrderTypeMenuService.updateWorkOrderType(userId, previousId, name, tenantId);
			//批量更新该工单类型的过滤器菜单中
			workOrderFilterMenuService.updateWorkOrderTypeByBatch(userId, previousId, name);
		}
		updateEditStatus(previousId, userId, 1);

//		//根绝流程实例id,关闭原类型id对应的流程引擎中的流程定义
//		WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(previousId);
//		ActiviVo activiVo = ActCommonUtils.startProcessInstance("_" + workOrderTypeVo.getName() + previousId, userId);
//		String processInstanceId = activiVo.getProcessInstId();
//		ActCommonUtils.closeXml(processInstanceId);

		//删除类型id对应的node节点
//		workOrderTypeNodeDao.deleteByWorkOrderTypeId(previousId);

		//更新原类型id对应的工单类型
		createOrUpdateWorkOrderType(2, jsonObject);
		// 推送关键操作日志至工作台
		WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(previousId);
		StringBuffer content = new StringBuffer();
		if (workOrderTypeVo!=null) {
			content.append(workOrderTypeVo.getName());
		}
		SysOptLogDto sysOptLogDto = new SysOptLogDto(userId,
				"修改的工单类型id为："+previousId,
				ConstantCode.SysOptLog.SERVICE_TYPE_EDIT
				, content.toString(), ConstantCode.SysOptLog.STATUS_SUCESS,
				null,tenantId,ConstantCode.SysOptLog.OPT_MODULE_ORDER_TYPE);
		eripDataSynService.recordSysOptLog(sysOptLogDto);

		return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.UPDATE_SUCCESS_MSG);
	}

	@Override
	public Integer updateDeleteStatus(Long id, String userId) {
		WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(id);
		EwsUser ewsUser = ewsUserDao.selectById(userId);
		workOrderTypeVo.setLastUserId(userId);
		workOrderTypeVo.setLastUserName(ewsUser.getName());
		Timestamp time = new Timestamp(System.currentTimeMillis());
		workOrderTypeVo.setLastUpdateTime(time);
		workOrderTypeVo.setDeleteStatus(1);
		Integer result = workOrderTypeDao.updateDeleteStatus(workOrderTypeVo);
		workOrderTypeNodeDao.deleteByWorkOrderTypeId(id);
		workOrderTypeMenuDao.deleteWorkOrderType(id);
		workOrderFilterMenuDao.deleteByWorkOrderTypeId(id);
		return result;
	}

	/**
	 * TODO 批量删除工单类型
	 * @author: victor_tang
	 * @createtime: 2020/5/20 15:06
	 * @param workOrderTypeInputDto 1
	 * @return: com.egoo.ews.service.utils.common.DbResponse
	 */
	@Override
	public DbResponse deleteBatch(WorkOrderTypeInputDto workOrderTypeInputDto) {
		try {
			EwsUser ewsUser = ewsUserDao.selectById(workOrderTypeInputDto.getUserId());
			List<Long> workOrderTypeIdList = workOrderTypeInputDto.getIdList();
			Map<String, Object> updateMap = new HashMap<>(8);
			updateMap.put("ids",workOrderTypeIdList);
			updateMap.put("deleteStatus",ConstantCode.DELETED_OLD);
			updateMap.put("lastUserId",ewsUser.getId());
			updateMap.put("lastUserName",ewsUser.getName());
			updateMap.put("lastUpdateTime",new Timestamp(System.currentTimeMillis()));
			// 逻辑批量删除工单类型
			workOrderTypeDao.batchUpdateDeleteStatusBatch(updateMap);

			Map<String, Object> deleteMap = new HashMap<>(2);
			deleteMap.put("workOrderTypeIds",workOrderTypeIdList);
			// 批量删除工单类型菜单
			workOrderTypeMenuDao.deleteByCondition(deleteMap);
			// 批量删除过滤器菜单
			workOrderFilterMenuDao.deleteByCondition(deleteMap);

			return new DbResponse(ResponseConstant.RES_SUCCESS_CODE, ResponseConstant.DEL_SUCCESS_MSG);
		} catch (Exception e) {
			log.error("删除工单类型异常："+e);
			return new DbResponse(ResponseConstant.RES_FAIL_CODE, "删除工单类型异常："+e);
		}
	}

	/**
	 * TODO 根据不同条件获取工单类型列表
	 *
	 * @param searchMap 1
	 * @author: victor_tang
	 * @createtime: 2020/2/16 14:02
	 * @return: java.utils.List<com.egoo.ews.service.vo.WorkOrderTypeVo>
	 */
	@Override
	public List<WorkOrderTypeVo> getWorkOrderTypeListByCondition(Map<String, Object> searchMap) {
		return workOrderTypeDao.selectWorkOrderTypeListByCondition(searchMap);
	}

	/**
	 * 获取所有的工单类型名字
	 *
	 * @return
	 */
	@Override
	public List<WorkOrderTypeVo> selectAllName(String tenantId) {
		return workOrderTypeDao.selectAllName(tenantId);
	}

	/**
	 * 获取所有可选择的工单类型(包含全部类型)
	 *
	 * @return
	 */
	@Override
	public List<InteractiveDataVo> selectAllSelectable(String tenantId) {
		List<InteractiveDataVo> interactiveDataList = new ArrayList<>();
		InteractiveDataVo interactiveData = new InteractiveDataVo();
		interactiveData.setValue(ConstantCode.UserRoleDeptType.ALL);
		interactiveData.setLabel(ConstantCode.UserRoleDeptType.ALL_ZH);
		interactiveDataList.add(interactiveData);
		List<InteractiveDataVo> interactiveDataList1 = workOrderTypeDao.selectAllSelectable(tenantId);
		interactiveDataList.addAll(interactiveDataList1);
		return interactiveDataList;
	}

	/**
	 * 更新工单类型的启停状态
	 *
	 * @param id
	 * @param useStatus
	 * @return
	 */
	public Integer updateContent(Long id, Integer useStatus) {
		WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(id);
//		JSONObject content = JSON.parseObject(workOrderTypeVo.getContentString());
		JSONObject content = workOrderTypeVo.getContent();

		content.getJSONObject("workordertypeformInfo").put("workordertypeEnable", useStatus + "");
//		workOrderTypeVo.setContentString(content.toJSONString());
		workOrderTypeVo.setContent(content);
		return workOrderTypeDao.updateContent(workOrderTypeVo);
	}

	@Override
	public String selectStartNodeId(String workOrderTypeId) {
		if(StringUtils.isEmpty(workOrderTypeId)){
			return null;
		}
		WorkOrderTypeVo workOrderTypeVo = workOrderTypeDao.selectById(Long.valueOf(workOrderTypeId));
		JSONObject content = workOrderTypeVo.getContent();
		JSONObject newworkordernodeInfo = content.getJSONObject("newworkordernodeInfo");
		String nodeId = newworkordernodeInfo.getString("uuid");

		return nodeId;
	}
}
